/*
 * @Author: your name
 * @Date: 2021-08-17 20:45:07
 * @LastEditTime: 2021-11-20 13:33:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /blogServe/src/service/moment.service.js
 */
const connection = require('../app/database');

class MomentService {
  async create(content, userId, label, classification, instructions) {
    const statement = `INSERT INTO moment (content, user_id, label, classification, instructions) VALUES (?, ?, ?, ?, ?);`;
    console.log("000");
    const [result]= await connection.execute(statement, [content, userId,  label, classification, instructions]);
    return result;
  }

  // 根据id查询数据并查询出是谁发表的
  async getMomentById(id) {
    const statement = `
    SELECT 
      m.id id, m.content content, m.label label, m.classification classification, 
      m. instructions instructions,
      m.createAt createTime, m.updataAt upataTime,
      JSON_OBJECT('id', u.id, 'name', u.name) author
    FROM moment m
    LEFT JOIN users u ON m.user_id = u.id
    WHERE m.id= ?;
    `;
    const [result]= await connection.execute(statement, [id]);
    return result[0];
  }

  // 分页查询列表数据
  async getMomentList(offset, size) {
    const statment = `
      SELECT 
        m.id id, m.content content, m.label label, m.classification classification, 
        m. instructions instructions,
        m.createAt createTime, m.updataAt upataTime,
        JSON_OBJECT('id', u.id, 'name', u.name) user
      FROM moment m
      LEFT JOIN users u ON m.user_id = u.id
      LIMIT ?, ?;
    `;
    const [result] = await connection.execute(statment, [offset, size]);
    return result;
  }
  // 修改动态
  async update(content, momentId) {
    const statement = `UPDATE moment SET content = ? WHERE id = ?;`
    const [result] = await connection.execute(statement, [content, momentId]);
    return result;
  }

  // 删除动态
  async remove(momentId) {
    const statement = `DELETE FROM moment WHERE id = ?;`
    const [result] = await connection.execute(statement, [momentId]);
    return result;
  }
}

module.exports = new MomentService();